#!/usr/bin/env python3
"""
SimpleAPI CLI工具

基于Typer的命令行界面，提供测试、服务器管理等功能。
"""

import typer
import sys
import os
from pathlib import Path
from typing import Optional, List
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich import print as rprint

from .simpleapi_test import SimpleApiTest

# 创建主应用和控制台
app = typer.Typer(
    name="simpleapi",
    help="SimpleAPI 命令行工具 - 提供测试、服务器管理等功能",
    add_completion=False
)
console = Console()

# 添加主要的test命令，直接运行测试
@app.command("test")
def test_main(
    test_dir: str = typer.Option(
        "tests", 
        "--dir", "-d",
        help="测试文件目录"
    ),
    pattern: str = typer.Option(
        "test_*.py",
        "--pattern", "-p", 
        help="测试文件名模式"
    ),
    verbosity: int = typer.Option(
        2,
        "--verbosity", "-v",
        min=0, max=2,
        help="输出详细程度 (0=静默, 1=正常, 2=详细)"
    ),
    safe_mode: bool = typer.Option(
        False,
        "--safe",
        help="安全模式：跳过可能有问题的测试"
    ),
    exit_on_failure: bool = typer.Option(
        True,
        "--exit-on-failure/--no-exit-on-failure",
        help="测试失败时是否退出"
    ),
    list_tests: bool = typer.Option(
        False,
        "--list", "-l",
        help="列出所有测试用例而不运行"
    ),
    test_file: str = typer.Option(
        None,
        "--file", "-f",
        help="运行指定的测试文件"
    )
):
    """运行测试用例 - SimpleAPI的主要测试命令"""
    
    console.print(Panel.fit(
        "[bold blue]🚀 SimpleAPI 测试工具[/bold blue]",
        border_style="blue"
    ))
    
    try:
        # 如果指定了测试文件
        if test_file:
            console.print(Panel.fit(
                f"[bold blue]🧪 运行测试文件: {test_file}[/bold blue]",
                border_style="blue"
            ))
            
            if not os.path.exists(test_file):
                console.print(f"[bold red]❌ 测试文件不存在: {test_file}[/bold red]")
                raise typer.Exit(1)
            
            test_runner = SimpleApiTest(verbosity=verbosity)
            test_runner.add_test_file(test_file)
            result = test_runner.run(exit_on_failure=False)
            
            if result.wasSuccessful():
                console.print("\n[bold green]🎉 测试文件运行成功！[/bold green]")
                raise typer.Exit(0)
            else:
                failed_count = len(result.failures + result.errors)
                console.print(f"\n[bold red]❌ 有 {failed_count} 个测试失败[/bold red]")
                raise typer.Exit(1)
        
        # 如果只是列出测试用例
        if list_tests:
            console.print(Panel.fit(
                "[bold blue]📋 发现的测试用例[/bold blue]",
                border_style="blue"
            ))
            
            test_runner = SimpleApiTest(test_directory=test_dir, verbosity=1)
            test_names = test_runner.list_tests()
            
            if not test_names:
                console.print(f"[yellow]在目录 '{test_dir}' 中没有发现测试用例[/yellow]")
                return
            
            # 创建表格显示测试用例
            table = Table(show_header=True, header_style="bold magenta")
            table.add_column("序号", style="dim", width=6)
            table.add_column("测试用例名称", style="cyan")
            table.add_column("所属文件", style="green")
            
            for i, test_name in enumerate(test_names, 1):
                # 尝试从测试名称中提取文件信息
                parts = test_name.split('.')
                if len(parts) >= 2:
                    file_name = parts[0] if parts[0].startswith('test_') else 'unknown'
                    test_method = parts[-1]
                else:
                    file_name = 'unknown'
                    test_method = test_name
                    
                table.add_row(str(i), test_method, file_name)
            
            console.print(table)
            console.print(f"\n[bold green]总共发现 {len(test_names)} 个测试用例[/bold green]")
            return
        
        # 默认：运行所有测试
        console.print(f"📁 扫描测试目录: [cyan]{test_dir}[/cyan]")
        console.print(f"🔍 文件模式: [cyan]{pattern}[/cyan]")
        
        if safe_mode:
            console.print("🛡️  [yellow]安全模式：将跳过可能有问题的并发测试[/yellow]")
        
        # 创建测试运行器
        test_runner = SimpleApiTest(
            test_directory=test_dir,
            verbosity=verbosity
        )
        
        # 运行测试
        result = test_runner.run(exit_on_failure=not safe_mode and exit_on_failure)
        
        # 显示结果
        if result.wasSuccessful():
            console.print("\n[bold green]🎉 所有测试都通过了！[/bold green]")
            raise typer.Exit(0)
        else:
            failed_count = len(result.failures + result.errors)
            console.print(f"\n[bold red]❌ 有 {failed_count} 个测试失败[/bold red]")
            
            if safe_mode:
                console.print("[yellow]🛡️  安全模式：忽略测试失败[/yellow]")
                raise typer.Exit(0)
            else:
                raise typer.Exit(1)
                
    except KeyboardInterrupt:
        console.print("\n[yellow]⚠️  测试被用户中断[/yellow]")
        raise typer.Exit(130)
    except Exception as e:
        console.print(f"\n[bold red]❌ 运行测试时发生错误: {e}[/bold red]")
        if verbosity >= 2:
            import traceback
            console.print(traceback.format_exc())
        raise typer.Exit(1)





@app.command("version")
def version():
    """显示版本信息"""
    console.print(Panel.fit(
        "[bold blue]SimpleAPI CLI v1.0.0[/bold blue]\n"
        "[dim]基于 Typer 构建的命令行工具[/dim]",
        border_style="blue"
    ))


@app.command("info")
def info():
    """显示项目信息"""
    
    # 检查项目结构
    project_info = []
    
    if os.path.exists("simpleapi"):
        project_info.append("✅ SimpleAPI 核心模块")
    else:
        project_info.append("❌ SimpleAPI 核心模块未找到")
    
    if os.path.exists("tests"):
        test_files = [f for f in os.listdir("tests") if f.startswith("test_") and f.endswith(".py")]
        project_info.append(f"✅ 测试目录 ({len(test_files)} 个测试文件)")
    else:
        project_info.append("❌ 测试目录未找到")
    
    if os.path.exists("requirements.txt"):
        project_info.append("✅ 依赖文件")
    else:
        project_info.append("❌ 依赖文件未找到")
    
    info_text = "\n".join(project_info)
    
    console.print(Panel(
        f"[bold blue]📊 SimpleAPI 项目信息[/bold blue]\n\n{info_text}",
        border_style="blue",
        padding=(1, 2)
    ))


def main():
    """CLI入口点"""
    app()


if __name__ == "__main__":
    main() 